package side;

import form.GUI;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import services.Command;
import services.Host;

public class listFile {

    private static final String FILE_DIR = ".//";

    public void listFile(String ext) {

        GenericExtFilter filter = new GenericExtFilter(ext);
        File dir = new File(".//");

        if (dir.isDirectory() == false) {
            System.out.println("Directory does not exists : " + FILE_DIR);
            return;
        }

        // list out all the file name and filter by the extension
        String[] list = dir.list(filter);
        if (list.length == 0) {
            System.out.println("no files end with : " + ext);
            return;
        }
      

        for (String file : list) {
            //     System.out.println("file : " + file);
            if (file.contains("default.json") && !file.isEmpty()) {
                Command.def.setFile(null);
                Command.def.setFile(JacksonStream.readJson("default.json"));
            } else {
                for (Host h : Command.clientList) {
                    String md5;
                    if (file.trim().equals(h.getIp().trim() + ".json") && !h.getIp().equals(Command.def.getIp())) {
                        if (file.equals(h.getIp().trim() + ".json")) {

                            h.setFile(null);
                            File f = new File(file);
                            if (f.exists()) {
                                //              System.out.append("Plik istnieje: "+file +"\n");
                                h.setFile(null);
                                h.setFile(JacksonStream.readJson(file));
                                try {
                                    md5 = side.SideDish.md5(file);
                                    h.setMD5(md5);
                                } catch (IOException ex) {
                                    Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                                }
                            } else {
                                System.out.append("brak pliku\n");
                            }


                        }
                        //    System.out.println("------------> Arraylist set in: " + h.getIp());
                    }
                }

            }

        }
    }

    // inner class, generic extension filter
    public class GenericExtFilter implements FilenameFilter {

        private String ext;

        public GenericExtFilter(String ext) {
            this.ext = ext;
        }

        public boolean accept(File dir, String name) {
            return (name.endsWith(ext));
        }
    }
}